package com.api.apigateway.mq;


import com.api.apigateway.enums.GateWayRefreshEnum;
import com.api.apigateway.service.RouteService;
import com.api.common.constant.APIInterfaceMqConstant;
import com.api.common.model.entity.InterfaceInfo;
import com.google.gson.Gson;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author: 崔老爷
 * Date: 2024/10/18 13:39
 * @Description:
 */
@Component
@Slf4j
public class APIDynamicRouteMessageConsumer {
    @Resource
    private RouteService routeService;


    @RabbitListener(queues = {APIInterfaceMqConstant.API_DYNAMIC_ROUTE_QUEUE}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
        log.info("开始处理添加路由消息: exchange={} queue={} route_key={}, deliveryTag={}, messageLength={}",
                APIInterfaceMqConstant.API_INTERFACE_LOG_EXCHANGE,
                APIInterfaceMqConstant.API_INTERFACE_LOG_QUEUE,
                APIInterfaceMqConstant.API_INTERFACE_LOG_ROUTE_KEY,
                deliveryTag,
                message != null ? message.length() : 0);

        if (StringUtils.isBlank(message)) {
            //空的消息没有必要再放到队列中
            channel.basicNack(deliveryTag, false, false);
//            throw new BusinessException(ErrorCode.OPERATION_ERROR, "消息为空");
        }

        try {
            Gson gson = new Gson();
            InterfaceInfo interfaceInfo = gson.fromJson(message, InterfaceInfo.class);
            Long id = interfaceInfo.getId();
            String host = interfaceInfo.getHost();
            String url = interfaceInfo.getUrl();
            routeService.addRoute(
                    String.format("api_route_%s", id),
                    host,
                    url
            );
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("消费接口日志消息失败: deliveryTag={}, message={}", deliveryTag, message, e);
            channel.basicNack(deliveryTag, false, true);
        }

    }

    /**
     * 接收刷网关的消息，（分布式情况下的刷新）
     *
     * @param message
     * @param channel
     * @param deliveryTag
     * @throws IOException
     */
    @RabbitListener(queues = {APIInterfaceMqConstant.API_DYNAMIC_REFRESH_ROUTE_QUEUE}, ackMode = "MANUAL")
    public void receiveRefreshGateWayMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
        log.info("开始处理刷新网关消息: exchange={} queue={} route_key={}, deliveryTag={}, messageLength={}",
                APIInterfaceMqConstant.API_INTERFACE_LOG_EXCHANGE,
                APIInterfaceMqConstant.API_DYNAMIC_REFRESH_ROUTE_QUEUE,
                APIInterfaceMqConstant.API_DYNAMIC_REFRESH_ROUTE_ROUTE_KEY,
                deliveryTag,
                message != null ? message.length() : 0);

        if (StringUtils.isBlank(message)|| !GateWayRefreshEnum.SUCCESS.getValue().equals(message)) {
            //空的消息没有必要再放到队列中
            log.error("消费接口日志消息失败: deliveryTag={}, message={}", deliveryTag, message);
            channel.basicNack(deliveryTag, false, false);
            return;
//            throw new BusinessException(ErrorCode.OPERATION_ERROR, "消息为空");
        }

        routeService.loadAndRefresh();
        channel.basicAck(deliveryTag, false);
    }
}
